import type { IUser, ICart,IAddress } from "@/types";
import type {InjectionKey} from "vue";
import { createStore, useStore as baseUseStore, Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import addressData from "./modules/address"
import orderData from "./modules/order"

// 为 store state 声明类型
export interface State {
    user: IUser,
    cart: {
        num: number,
        good: any
    }
}


// 定义 injection key
export const key: InjectionKey<Store<any>> = Symbol()

export const store = createStore<any>({
    state: {
        user: {
            aeskey: '',
            token: '', 
            uid: ''
        },
        cart: {
            good: [],
            num: 0
        }
    },
    mutations: {
        setUser(state :any, param: IUser) {
            let {uid, token} = param;
            state.user = {...param}
            localStorage.setItem('uid', JSON.stringify(uid));
            localStorage.setItem('token', JSON.stringify(token));
        },
        delUser(state:any) {
            state.user = {
                aeskey: '',
                token: '', 
                uid: ''
            }
            localStorage.removeItem('uid');
            localStorage.removeItem('token');
        },
        editCart(state: any, param: ICart) {
            state.cart = param;
        }
    },
    actions: {

    },
    modules: {
        addressData,
        orderData
    },
    plugins: [createPersistedState()],
})



// 定义自己的 `useStore` 组合式函数
export function useStore () {
    return baseUseStore(key)
  }


